import { Request, toast } from '../../utils/util.js'
let request = new Request()
let app = getApp()
let W = 0
let H = 0
Page({
  data: {
    storeQr : '',
    storeId: 0,
    query: {category : 0},
    user : {},
    goodsList : [],

    editting : false,

    isSelf : false,
    showQr : false
  },

  toggleEdit () {
    this.setData({editting : !this.data.editting})
  },

  changeCategory (categoryId) {
    this.setData({ 'query.category': categoryId})
    wx.nextTick(() => {
      let pagination = this.selectComponent('#pagination')
      this.setData({ goodsList: [] })
      pagination.initLoad()
    })
  },

  load(e) {
    let rows = e.detail.list
    let page = e.detail.page
    if (rows.length == 0 && page == 1) {
      this.setData({ goodsList: null})
      return
    }
    let goodsList = Object.assign([], this.data.goodsList)
    rows.forEach(row => {
      if(!row) {
        return
      }
      goodsList.push(row)
    })

    this.setData({ goodsList: goodsList })
  },

  deleteChat (e) {
    let index = e.currentTarget.dataset.index
    let chatId = this.data.goodsList[index].chat_id
    wx.showModal({
      title: '删除产品',
      content: '确定删除这个产品吗',

      success : (res) => {
        if(res.confirm) {
          request.delete('chat/delete', res => {
            if(res.success) {
              let goodsList = this.data.goodsList
              goodsList.splice(index, 1)
              this.setData({goodsList : goodsList})
              if(goodsList.length == 0) {
                this.selectComponent('#pagination').initLoad()
              }
            } else {
              toast(res.msg)
            }
          }, {chatId : chatId})
        }
      }
    })
  },

  edit (e) {
    let index = e.currentTarget.dataset.index
    let chatId = this.data.goodsList[index].chat_id
    wx.navigateTo({
      url: '/pages/publish/chat/index?chatId=' + chatId
    })
  },

  getStoreQr () {
    if (this.data.storeQr === '') {
      let req = new Request()
      req.setConfig('responseType', 'arraybuffer')
      req.get('store/qrcode', res => {
        let qrcode = wx.arrayBufferToBase64(res).replace(/[\r\n]/g, '')
        this.setData({ storeQr: qrcode, showQr: true })
      }).showLoading()
    }else{
      this.setData({showQr : true})
    }
    
  },

  draw() {
    let sef = this
    wx.showLoading()
    let qrcode = this.data.storeQr
    let avatar = this.data.user.avatar
    let nickname = this.data.user.nickname
    const query = wx.createSelectorQuery()
    query.select('#canvasEl').boundingClientRect()
    query.exec(function (res) {
      W = res[0].width
      H = res[0].height

      var ctx = wx.createCanvasContext('firstCanvas')

      //ctx.setFillStyle('#fff')
      //ctx.fillRect(0, 0, W, H)

      ctx.setFillStyle('#333333')
      ctx.setTextAlign('center')
      ctx.setFontSize(14)
      ctx.fillText(nickname, W / 2, 70, W)

      ctx.draw(true);

      wx.showLoading({
        title: ''
      })
      wx.getImageInfo({
        src: avatar,
        success: function (res) {
          ctx.drawImage(res.path, 0, 0, 132, 132, (W / 2 - 20), 10, 40, 40)
          ctx.draw(true);

          const fsm = wx.getFileSystemManager()
          const filePath = `${wx.env.USER_DATA_PATH}/storeQr.png`
          console.log(filePath)
          const buffer = wx.base64ToArrayBuffer(qrcode)
          fsm.writeFile({
            filePath,
            data: buffer,
            encoding: 'binary',
            success() {
              wx.getImageInfo({
                src: filePath,
                success: (res) => {
                  ctx.drawImage(res.path, 0, 0, 280, 280, (W / 2 - 60), 80, 120, 120)
                  ctx.draw(true)
                  wx.hideLoading()
                  sef.save()
                }
              })
            },
            fail (e) {
             
            }
          })

        }
      })


    })
  },

  save() {
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: W,
      height: H,
      destWidth: W,
      destHeight: H,
      canvasId: 'firstCanvas',
      success : (res) => {
        this.setData({ showQr: false })
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
          },
          fail() {
            toast('保存失败')
          }
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let storeId = options.storeId || 0
    if (storeId > 0 && storeId != app.globalData.userInfo.user_id) {
      this.setData({ query: { storeId: storeId }, storeId: storeId })
      request.get('user/user/' + storeId, res => {
        if (res.success) {
          let user = res.data.user
          if (!(user instanceof Object)) {
            user = JSON.parse(user)
          }

          this.setData({ user: user })
        }
      })
    }else{
      this.setData({ isSelf: true, user: app.globalData.userInfo})
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let pages = getCurrentPages()
    let page = pages[pages.length - 1]
    let to = encodeURIComponent('/' + page.route + '?storeId=' + this.data.storeId)
    let path = '/pages/index/index?path=' + to
    return {
      path: path
    }
  }
})